
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/10/23 09:08
# @Author  : supuchun
# @Site    :
# @File    : n2_create.py
from flask import Flask, request, jsonify
from n2 import HnswIndex
import time
import numpy as np
import os
import redis
import pymysql
import json,sys

def open_db():
    global db, cursor
    db = pymysql.connect("rm-2ze108d8naeso02i1o.mysql.rds.aliyuncs.com", "elephant", "K6hd562P1m", "compare_v2",charset='utf8')
    cursor = db.cursor()

def open_db_two():
    global ele_db, cur
    ele_db = pymysql.connect("rm-2ze108d8naeso02i1o.mysql.rds.aliyuncs.com", "elephant", "K6hd562P1m", "elephant_v2",charset='utf8')
    cur = ele_db.cursor()

def close_db():
    global db
    db.close()


# 写入消息队列，参数1：队列名称，参数2：消息内容
def get_data(company_id,spider_id):
    global db, cursor
    sql = """select oss_url,clue_id,task_id,pic_url from compare_v2.compare_%s where id =%s """ % (company_id,spider_id)
    # print(sql)
    # exit()
    try:
        # 执行sql语句
        cursor.execute(sql)
	result = cursor.fetchone()
        # 提交到数据库执行
        db.commit()
    except:
        # 如果发生错误则回滚
        print(sql)
        db.rollback()
        return False
    task_id = result[2]
    clue_id = result[1]
    data = {}
    data['oss_url'] = result[0]
    data['spider_img'] = result[3]
    sql = """select customer_name,principal_name from elephant_v2.ele_company  where id =%s """ % (company_id)
    # print(sql)
    # exit()
    try:
        # 执行sql语句
        cur.execute(sql)
        company_info = cur.fetchone()
        # 提交到数据库执行
        ele_db.commit()
    except:
        # 如果发生错误则回滚
        print(sql)
        ele_db.rollback()
        return False
    data['customre_name'] = company_info[0]
    data['principal_name'] = company_info[1]
    data['clue_id'] = clue_id
    sql = """select clue_type from elephant_v2.ele_task_clue where task_id =%s and clue_id =%s """ % (task_id,clue_id)
    try:
        # 执行sql语句
        cur.execute(sql)
        clue_info = cur.fetchone()
        # 提交到数据库执行
        ele_db.commit()
    except:
        # 如果发生错误则回滚
        print(sql)
        ele_db.rollback()
        return False
    data['clue_type']=clue_info[0]
    res = json.dumps(data)
    return res

app = Flask(__name__)


# start_run()

@app.route('/ann')
def compute():
    open_db()
    open_db_two()
    if 'company_id' in request.args  and 'spider_id' in request.args:
        return get_data(request.args['company_id'],request.args['spider_id'])
    else:
        return 'Input the correct URL..'


if __name__ == '__main__':
    # from werkzeug.contrib.fixers import ProxyFix
    # app.wsgi_app = ProxyFix(app.wsgi_app)
    app.run(host='0.0.0.0',port=8888, threaded=True)